import React, { Component } from 'react'
import { Menu } from 'antd';
import menuList from '../../config/menuConfig.jsx'
import memoryUtils from '../../utils/memoryUtils'
import { Link, withRouter } from 'react-router-dom';
import logo from './logo.png';
import './index.less';

const { SubMenu } = Menu;
class LeftNav extends Component {
	getMenuNodes_map = (menuList) => {
		return (
			<Menu
				mode="inline" theme="dark" inlineCollapsed={this.state.collapsed}>
				{
					menuList.map((item) => {
						if (!item.children) {
							return (
								<Menu.Item key={item.key} icon={item.icon}>
									<Link to={item.key}>{item.title}</Link>
								</Menu.Item>
							)
						}
						else {
							return (
								<SubMenu key={item.key} title={item.title} icon={item.icon}>
									{this.getMenuNodes_map(item.children)}
								</SubMenu>
							)
						}
					})
				}
			</Menu>)

	}
	getMenuNodes_reduce = (menuList) => {
		const path = this.props.location.pathname
		return menuList.reduce((pre, item) => {
			if (this.hasAuth(item)) {
				if (!item.children) {
				pre.push((
					<Menu.Item key={item.key} icon={item.icon}>
						<Link to={item.key}>{item.title}</Link>
					</Menu.Item>
				))
			} else {
				if (item.children.find(
					(citem) =>citem.key === (path.indexOf(citem.key) === 0 ? citem.key : path))) {
					this.openKey = item.key
				}
				pre.push((
					<SubMenu key={item.key} title={item.title} icon={item.icon}>
						{this.getMenuNodes_reduce(item.children)}
					</SubMenu>
				))
			}
			}
			
			return pre
		}, [])
	}
	hasAuth=(item)=>{
		const {key,isPublic} = item
		const {menus} = memoryUtils.user.role
		const { username } = memoryUtils.user
		if (username === 'admin' || isPublic || menus.indexOf(key) !== -1) {
			 return true
		} else if (item.children) {
			
			return !!item.children.find(child=>menus.indexOf(child.key) !== -1)
		} else {
			return false
		}
	}
	render() {
		this.MenuNodes = this.getMenuNodes_reduce(menuList)
		let path = this.props.location.pathname !== '/' ? this.props.location.pathname : '/home'
		if (path.indexOf('/product') === 0) {
			path = '/product'
		}
		return (
			<div className='left-nav'>
				<Link to='/home'>
					<header className='left-nav-header'>
						<img src={logo} alt="logo" />
						<h1>React：后台管理系统</h1>
					</header>
				</Link>
				<div>
					{/* {this.getMenuNodes_map(menuList)} */}
					<Menu selectedKeys={[path]} defaultOpenKeys={[this.openKey]}
						mode="inline" theme="dark">
						{this.MenuNodes}
					</Menu>
				</div>
			</div>
		)
	}
}

export default withRouter(LeftNav)
